package com.wanli.storemobile.homepage;


import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wanli.storemobile.R;
import com.wanli.storemobile.base.BaseActivity;
import com.wanli.storemobile.base.DataCallBack;
import com.wanli.storemobile.bean.BankCardBean;
import com.wanli.storemobile.bean.BaseResponseBean;
import com.wanli.storemobile.bean.EBankStoreDataContacts;
import com.wanli.storemobile.bean.EBankStoreDataInfo;
import com.wanli.storemobile.bean.ImageBean;
import com.wanli.storemobile.bean.SettlementInfoBean;
import com.wanli.storemobile.bean.StoreDeatilsBean;
import com.wanli.storemobile.dialog.BankDepositDialog;
import com.wanli.storemobile.dialog.ChooseBankDialog;
import com.wanli.storemobile.event.ChooseBankEvent;
import com.wanli.storemobile.event.StoreNextEvent;
import com.wanli.storemobile.homepage.model.HomePageModelImpl;
import com.wanli.storemobile.homepage.model.IHomePageModel;
import com.wanli.storemobile.utils.Base64BitmapUtil;
import com.wanli.storemobile.utils.GlideEngine;
import com.wanli.storemobile.utils.GlideUtils;
import com.wanli.storemobile.utils.PermissionsManager;
import com.wanli.storemobile.utils.SPManager;
import com.wanli.storemobile.utils.ToastUtil;
import com.wanli.storemobile.widget.AppTitleBar;
import com.wanli.storemobile.widget.ViewLoading;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SettlementInfoActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.ic_prcture_4)
    ImageView icPrcture4;
    @BindView(R.id.ic_prcture_5)
    ImageView icPrcture5;
    @BindView(R.id.ic_prcture_6)
    ImageView icPrcture6;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.ll_bank_name)
    LinearLayout llBankName;
    @BindView(R.id.view_end_time)
    View viewEndTime;
    @BindView(R.id.edit_bank_username)
    EditText editBankUsername;
    @BindView(R.id.edit_bank_mobile)
    EditText editBankMobile;
    @BindView(R.id.edit_bank_idNumber)
    EditText editBankIdNumber;
    @BindView(R.id.edit_bank_num)
    EditText editBankNum;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.iv_bank_card_scan)
    ImageView iv_bank_card_scan;
    @BindView(R.id.tv_download_power_attorney_template)
    TextView tv_download_power_attorney_template;

    @BindView(R.id.iv_1)
    ImageView iv_1;
    @BindView(R.id.iv_2)
    ImageView iv_2;
    @BindView(R.id.iv_3)
    ImageView iv_3;
    private IHomePageModel homePageModel;

    private BottomSheetDialog selectPicDialog;
    private PermissionsManager permissionsManager;
    private String[] permissions;
    private int openType;//0 相册，1相机
    private List<LocalMedia> mediaList = new ArrayList<>();
    private String bank_card_front_pic;
    private String bank_card_back_pic;
    private String yinsheng_change_pic;

    private String bankName;
    private String bankType;

    public String branchName;
    public String branchCity;
    public String branchProvince;
    public String unionpay;
    private ArrayList<String> options4Items = new ArrayList<>();
    private String holder;
    private String holder_mobile;
    private String holder_id_card_no;
    private String bank_card_no;
    private String branchCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settlement_info);
        ButterKnife.bind(this);
        initView();
        initData();

        initEvent();
    }

    private void initEvent() {

        iv_bank_card_scan.setOnClickListener(v -> {
            imgType = 4;
            showPictureSelectorDialog();
        });
        iv_1.setOnClickListener(v -> {
            Intent intent = new Intent(this, PreviewPicturesActivity.class);
            intent.putExtra("type","5");
            startActivity(intent);
        });
        iv_2.setOnClickListener(v -> {
            Intent intent = new Intent(this, PreviewPicturesActivity.class);
            intent.putExtra("type","6");
            startActivity(intent);

        });
        iv_3.setOnClickListener(v -> {
            Intent intent = new Intent(this, PreviewPicturesActivity.class);
            intent.putExtra("type","11");
            startActivity(intent);
        });

        tv_download_power_attorney_template.setOnClickListener(v -> {
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.iv_bgsqb);
            saveScreenShot(bmp);
        });
    }

    private void initView() {
        homePageModel = new HomePageModelImpl();
        permissionsManager = new PermissionsManager(SettlementInfoActivity.this);

        options4Items.add("个人账户");
        options4Items.add("公司账户");

    }


    public void initData() {
        homePageModel.requestGetStlInfo(new DataCallBack<SettlementInfoBean>() {
            @Override
            public void onSuccessful(SettlementInfoBean bean) {
                if (bean.getData() != null) {
                    if (isDestroy()) {
                        return;
                    }
                    bankName = bean.getData().getBank();
                    bankType = bean.getData().getBank_type();
                    branchName = bean.getData().getBranch();
                    branchProvince = bean.getData().getBranch_province();
                    branchCity = bean.getData().getBranch_city();
                    unionpay = bean.getData().getUnionpay();
                    tvBankName.setText(branchName);
                    bank_card_front_pic = bean.getData().getBank_card_front_pic();
                    bank_card_back_pic = bean.getData().getBank_card_back_pic();
                    yinsheng_change_pic = bean.getData().getYinsheng_change_pic();
                    GlideUtils.loadImage(mActivity, icPrcture4, bean.getData().getBank_card_front_pic());
                    GlideUtils.loadImage(mActivity, icPrcture5, bean.getData().getBank_card_back_pic());
                    GlideUtils.loadImage(mActivity, icPrcture6, bean.getData().getYinsheng_change_pic());
                    editBankUsername.setText(bean.getData().getHolder());
                    editBankMobile.setText(bean.getData().getHolder_mobile());
                    editBankIdNumber.setText(bean.getData().getHolder_id_card_no());
                    editBankNum.setText(bean.getData().getBank_card_no());
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Subscribe
    public void onChooseBankEvent(ChooseBankEvent event) {
        tvBankName.setText(event.getBankBranch());
    }
    int imgType;
    @OnClick({R.id.ic_prcture_4,R.id.ic_prcture_5, R.id.ic_prcture_6,  R.id.ll_bank_name, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ic_prcture_4:
                imgType = 4;
                showPictureSelectorDialog();
                break;
            case R.id.ic_prcture_5:
                imgType = 5;
                showPictureSelectorDialog();
                break;
            case R.id.ic_prcture_6:
                imgType = 6;
                showPictureSelectorDialog();
                break;
            case R.id.ll_bank_name:

                BankDepositDialog dialog = BankDepositDialog.newInstance("0");

                dialog.show(getSupportFragmentManager(), "dialog");

                dialog.setOnCallBackListener((branch_province, branch_city, open_acc_area, bank_name, bank_type, open_acc_bank_name, open_acc_bank_type) -> {



                    bankName = bank_name;
                    bankType = bank_type;
                    branchName = open_acc_bank_name;


                    branchProvince = branch_province;
                    branchCity = branch_city;


                    tvBankName.setText(open_acc_bank_name);
                    branchCode = open_acc_bank_type;


                    Log.e("-----branch_province", branch_province);
                    Log.e("-----branch_city", branch_city);
                    Log.e("-----open_acc_area", open_acc_area);
                    Log.e("-----bank_name", bank_name);
                    Log.e("-----bank_type", bank_type);
                    Log.e("-----open_acc_bank_name", open_acc_bank_name);
                    Log.e("-----open_acc_bank_type", open_acc_bank_type);

                });

                break;
            case R.id.tv_commit:
                if (TextUtils.isEmpty(bank_card_front_pic)) {
                    ToastUtil.showShort("请上传银行卡正面照片");
                    return;
                }
                if (TextUtils.isEmpty(bank_card_back_pic)) {
                    ToastUtil.showShort("请上传银行卡背面照片");
                    return;
                }
                if (TextUtils.isEmpty(yinsheng_change_pic)) {
                    ToastUtil.showShort("请上传信息变更申请表图片");
                    return;
                }

                if (TextUtils.isEmpty(branchName)) {
                    ToastUtil.showShort("请选择银行");
                    return;
                }
                holder = editBankUsername.getText().toString();
                if (TextUtils.isEmpty(holder)) {
                    ToastUtil.showShort("请输入开户名");
                    return;
                }
                holder_mobile = editBankMobile.getText().toString();
                if (TextUtils.isEmpty(holder_mobile)) {
                    ToastUtil.showShort("请输入开户预留电话");
                    return;
                }
//                holder_id_card_no = editBankIdNumber.getText().toString();
//                if (TextUtils.isEmpty(holder_id_card_no)) {
//                    ToastUtil.showShort("请输入开户人身份证号");
//                    return;
//                }
                bank_card_no = editBankNum.getText().toString();
                if (TextUtils.isEmpty(bank_card_no)) {
                    ToastUtil.showShort("请输入开户人身份证号");
                    return;
                }
                requestChangeStlInfo();
                break;
        }
    }

    public void requestChangeStlInfo() {
        ViewLoading.showProgress(mActivity, "修改中......");
        homePageModel.requestChangeStlInfo("0", bank_card_front_pic,  bank_card_back_pic,yinsheng_change_pic,holder, holder_mobile, "", branchProvince, branchCity, bankName, bankType,branchName, bank_card_no, unionpay, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort(bean.getMsg());
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    if (mediaList.size() > 0) {
                        String imgPath = mediaList.get(0).getCompressPath();
                        requestUploadFile(imgPath);
                    }
                    break;
            }
        }

    }

    /**
     * 上传图片
     */
    public void requestUploadFile(String imgPath) {
        ViewLoading.showProgress(mActivity, "上传中......");
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        String file = Base64BitmapUtil.bitmapToBase64(bitmap);
        homePageModel.requestUploadFile("store", file, new DataCallBack<ImageBean>() {
            @Override
            public void onSuccessful(ImageBean bean) {
                ToastUtil.showShort("上传成功");

                if (imgType==4){
                    bank_card_front_pic = bean.getData();
                    GlideUtils.loadImage(mActivity, icPrcture4, imgPath);
                    requestAliBankCard(bean.getData());
                }else if (imgType==5){
                    bank_card_back_pic = bean.getData();
                    GlideUtils.loadImage(mActivity, icPrcture5, imgPath);
                }else if (imgType==6){
                    yinsheng_change_pic = bean.getData();
                    GlideUtils.loadImage(mActivity, icPrcture6, imgPath);
                }

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestAliBankCard(String imgPath) {
        homePageModel.requestAliBankCard(imgPath, new DataCallBack<BankCardBean>() {
            @Override
            public void onSuccessful(BankCardBean bean) {
                if (bean.getData() != null && bean.getData().isSuccess()) {
                    ToastUtil.showShort("识别成功");
                    editBankNum.setText(bean.getData().getCard_num());
                    if (!TextUtils.isEmpty(bean.getData().getCard_num())) {
                        editBankNum.setSelection(bean.getData().getCard_num().length());
                    }

                } else {
                    ToastUtil.showShort("识别失败，请输入");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private void showPictureSelectorDialog() {

        selectPicDialog = new BottomSheetDialog(mActivity, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    /**
     * 点击相机
     */
    private void handlerCameraClick() {
        openType = 1;
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {
        openType = 0;
        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(SettlementInfoActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }

    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(SettlementInfoActivity.this)//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    @Override
    public void handlerPermissionForActivityResult() {
        if (PermissionsManager.checkPermissions(permissions)) {
            if (openType == 0) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else if (openType == 1) {
                openCamera();
                cancelPictureDialog();
            }
        }
    }
    /**
     * 屏幕截图保存
     */
    private void saveScreenShot(Bitmap bitmap) {
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        OutputStream outStream = null;
        String filename;//声明文件名
        //以保存时间为文件名
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        filename = sdf.format(date);
        File file = new File(extStorageDirectory, filename + ".JPEG");//创建文件，第一个参数为路径，第二个参数为文件名
        try {
            outStream = new FileOutputStream(file);//创建输入流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
            outStream.close();

            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            mActivity.sendBroadcast(intent);

            Toast.makeText(mActivity, "保存成功 打开相册查看", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(mActivity, "exception:" + e,
                    Toast.LENGTH_SHORT).show();

        }
    }
}
